<?php
namespace app\common\command;

use app\common\repository\post\PostsRepository;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Workerman\Timer;
use Workerman\Worker;
use Workerman\Crontab\Crontab;

class PostHotScore extends Command
{
    protected function configure(): void
    {
        $this->setName('timer:posts')
            ->setDescription('动态定时任务');
    }

    protected function execute(Input $input, Output $output): void
    {
        /**
         * 0   1   2   3   4   5
         * |   |   |   |   |   |
         * |   |   |   |   |   +------ day of week (0 - 6) (Sunday=0)
         * |   |   |   |   +------ month (1 - 12)
         * |   |   |   +-------- day of month (1 - 31)
         * |   |   +---------- hour (0 - 23)
         * |   +------------ min (0 - 59)
         * +-------------- sec (0-59)[可省略，如果没有0位,则最小时间粒度是分钟]
         */
        $worker = new Worker();
        $worker->onWorkerStart = function () use ($output) {
            // 每一个小时
            new Crontab('0 * * * *', function () use ($output) {
                $this->updatePostHotScore();
                $output->writeln('[' . date('Y-m-d H:i:s') . '] 帖子热度更新完成');
            });
            // 每天晚上24：00
            new Crontab('0 0 * * *', function () use ($output) {
                $this->calibrateTagWeights();
                $output->writeln('[' . date('Y-m-d H:i:s') . '] 标签权重更新完成');
            });
        };

        // 运行 Worker
        Worker::runAll();
    }

    /**
     * 批量更新帖子热度分数
     *
     * @return void
     * @throws \think\db\exception\DbException
     */
    protected function updatePostHotScore(): void
    {
        $postsRepository = app()->make(PostsRepository::class);
        $postsRepository->batchUpdateHotScores();
        // 记录日志
        \think\facade\Log::write('定时任务：已更新动态热度分数', 'info');
    }

    /**
     * 更新标签权重值
     *
     * @return void
     */
    protected function calibrateTagWeights(): void
    {
        $postsRepository = app()->make(PostsRepository::class);
        $postsRepository->calibrateTagWeights();
        // 记录日志
        \think\facade\Log::write('定时任务：已更新标签权重', 'info');
    }
}